package com.venus.component.htmltag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.venus.component.page.PageInfo;

public class SplitPageTag extends TagSupport {
	
	private static final long serialVersionUID = 1L;

	/** PageInfo实例保存在request中的名称 */
	private String name ;
	
	/** 页面上待提交的form表单ID */
	private String formId;
	
	/** log */
	protected final Log log = LogFactory.getLog(getClass());
	
	@Override
	public int doStartTag() throws JspException {
		Object object = this.pageContext.getRequest().getAttribute(name);
		if(object!=null){
			PageInfo objPageInfo = (PageInfo) object;
			StringBuffer sb = new StringBuffer(256);
			if(objPageInfo.getCurPage() != 1){
				sb.append("<a href='#' onclick='splitPage(1)'>首页</a>&nbsp;");
				sb.append("<a href='#' onclick='splitPage("+objPageInfo.getPreviousPage()+")'>上一页</a>&nbsp;");
			}
			if(objPageInfo.getCurPage() != objPageInfo.getAllPage()){
				sb.append("<a href='#' onclick='splitPage("+objPageInfo.getNextPage()+")'>下一页</a>&nbsp;");
				sb.append("<a href='#' onclick='splitPage("+objPageInfo.getAllPage()+")'>末页</a>&nbsp;");
			}
			sb.append("当前<input class='validate[required,custom[number],min[1],max["+objPageInfo.getAllPage()+"]]' onkeypress='if(event.keyCode==13){splitPage(this.value)}' style='width: 20px' id='curPage' name='curPage' value='"+objPageInfo.getCurPage()+"'/>页,");
			sb.append("每页<input class='validate[required,custom[number],min[1]]' onkeypress='if(event.keyCode==13){splitPage(1)}' style='width: 20px' id='pageRecord' name='pageRecord' value='"+objPageInfo.getPageRecord()+"'/>条记录,");
			sb.append("共<font color='red'>"+objPageInfo.getAllRecord()+"</font>条记录,");
			sb.append("分<font color='red'>"+objPageInfo.getAllPage()+"</font>页");
			sb.append("<script>");
			sb.append("function splitPage(idx){$('#method').val('list');$('#curPage').val(idx);$('#"+this.formId+"').submit();}");
			sb.append("</script>");
			JspWriter objJspWriter = this.pageContext.getOut();
			try {
				objJspWriter.print(sb.toString());
			} catch (IOException e) {
				this.log.error("分页标签类写页面出错!");
				e.printStackTrace();
			}
		}else{
			log.error("没有找到request中保存的分页类,指定名称:"+name);
		}
		return super.doStartTag();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getFormId() {
		return formId;
	}

	public void setFormId(String formId) {
		this.formId = formId;
	}
	
	
}
